package com.example.demo.controller;

import com.example.demo.pojo.FileBean;
import com.example.demo.service.impl.FileServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;

@Controller
public class FileController {
    private final static Logger logger = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private ServletContext servletContext;

    @Autowired
    FileServiceImpl fileService;

    /**
     * 实现文件上传
     */
    @RequestMapping("fileUpload")
    public String fileUpload(@RequestParam("fileName") MultipartFile file, Model model) throws FileNotFoundException {
        if (file.isEmpty()) {
            logger.error("文件为空，上传失败");
            model.addAttribute("msg", "文件为空，上传失败");
            return "forward:index";
        }
        FileBean fileBean = new FileBean();
        String fileName = file.getOriginalFilename();
        if (fileService.getFileByName(fileName) != null) {
            logger.error("文件重复，上传失败");
            model.addAttribute("msg", "文件重复，上传失败");
            return "forward:index";
        }
        if (fileName.length() > 15) {
            logger.error("文件名太长，请将文件名修改至小于15个字符后，再次尝试上传");
            model.addAttribute("msg", "文件名太长，请将文件名修改至小于15个字符后，再次尝试上传");
            return "forward:index";
        }
        fileBean.setFileName(fileName);
        String webRootPath = servletContext.getRealPath("");
        File dest = new File(webRootPath + "/" + fileName);
        fileBean.setSrc(webRootPath + "" + fileName);
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            fileService.addFile(fileBean);
            model.addAttribute("fileList", fileService.getFileList());
            return "forward:index";
        } catch (IllegalStateException e) {
            model.addAttribute("msg", "error");
            logger.error("IllegalStateException:error");
            e.printStackTrace();
            return "forward:index";
        } catch (IOException e) {
            model.addAttribute("msg", "error");
            e.printStackTrace();
            logger.error("IOException:error");
            return "forward:index";
        }
    }

    //文件下载
    @RequestMapping("dowload")
    public String dowload(HttpServletResponse response, String id, Model model) throws IOException {
        FileBean files = fileService.getFileByName(id);
        System.out.println(files);
        String Path = files.getSrc();
        File f = new File(Path);
        if (f.exists()) {
            logger.info("开始下载");
            FileInputStream fis = new FileInputStream(f);
            String filename = URLEncoder.encode(f.getName(), "utf-8"); //解决中文文件名下载后乱码的问题
            byte[] b = new byte[fis.available()];
            fis.read(b);
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filename + "");
            //获取响应报文输出流对象
            ServletOutputStream out = response.getOutputStream();
            //输出
            out.write(b);
            out.flush();
            out.close();
        } else {
            logger.info("文件不存在，请稍后再试");
            model.addAttribute("msg", "文件不存在，请稍后再试");
        }
        return "forward:index";
    }

}
